package readwritelock;

import com.sun.org.apache.bcel.internal.generic.NEW;

import java.io.ObjectInputValidation;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * @Author ufo
 * @Description TODO
 * @Date 2021/1/21 10:18
 * @Version 1.0
 */
public class rwlockTest {

    public static void main(String[] args) {
        Mycache2 rwlockTest = new Mycache2();

        for (int i = 0; i < 10; i++) {
            final int tmp = i;
            new Thread(() -> {
                rwlockTest.put(String.valueOf(tmp), "fbviewbfuwe");
            }, String.valueOf(i)).start();
        }

        for (int i = 0; i < 10; i++) {
            final int tmp = i;
            new Thread(() -> {
                rwlockTest.get(String.valueOf(tmp));
            }, String.valueOf(i)).start();
        }


    }

}

//没加读写锁
class Mycache {
    private volatile Map<String, Object> map = new HashMap<>();


    //写入
    public void put(String key, Object value) {
        System.out.println(Thread.currentThread().getName()+"写入中"+key);
        map.put(key, value);
        System.out.println(Thread.currentThread().getName()+"写入完毕"+key);

    }

    //读出
    public void get(String key) {
        System.out.println(Thread.currentThread().getName()+"读取中"+key);

        Object o = map.get(key);
        System.out.println(Thread.currentThread().getName()+"读取完毕"+key);

    }

}

//加了读写锁
class Mycache2 {
    private volatile Map<String, Object> map = new HashMap<>();
    ReadWriteLock lock=new ReentrantReadWriteLock();

    //写入
    public void put(String key, Object value) {
        lock.writeLock().lock();

        try {
            System.out.println(Thread.currentThread().getName()+"写入中"+key);
            map.put(key, value);
            System.out.println(Thread.currentThread().getName()+"写入完毕"+key);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.writeLock().unlock();
        }

    }

    //读出
    public void get(String key) {
        lock.readLock().lock();
        try {
            System.out.println(Thread.currentThread().getName()+"读取中"+key);
            Object o = map.get(key);
            System.out.println(Thread.currentThread().getName()+"读取完毕"+key);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.readLock().unlock();
        }

    }

}
